<template>
  <ContentWrap>
    <el-form :model="queryParams" ref="queryFormRef" label-width="auto" :inline="true">
      <el-form-item label="客户编号" prop="customerNo">
        <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" :clearable="true" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" :clearable="true" />
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['customer:customerPool:list']" @click="handleClickSearch">
          <Icon icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="handleClickReset">
          <Icon icon="ep:refresh" />
          重置
        </el-button>
        <el-button v-hasPermi="['customer:customerPool:receive']" @click="handleClickReceive">
          领取
        </el-button>
        <el-button v-hasPermi="['customer:customerPool:allocation']" @click="handleClickAllocation">
          分配
        </el-button>
        <el-button
          @click="handleClickRecycle"
          v-hasPermi="['customer:customerPool:recycleList']"
          :style="queryParams.isRecycle ? 'color:#E6A23C' : ''"
        >
          {{ recycleMessage }}
        </el-button>
      </el-form-item>
    </el-form>
    <Table
      ref="tableRef"
      :columns="columns"
      :page-param="queryParams"
      :adaptive="true"
      :page-data="queryData"
      save-key="customer"
      height-per="90"
      @page-change="getPage"
      @row-click="handleTableClick"
    >
      <template #mainImageUrl="{ row }">
        <span v-if="row.images.length == 0"></span>
        <el-image
          v-else
          preview-teleported
          loading="lazy"
          :src="row.images[0].url"
          :preview-src-list="[row.images[0].url]"
          fit="cover"
          class="w-[100px] h-[100px]"
        />
      </template>
      <template #menu="{ row }">
        <context-menu-item
          label="放入回收站"
          @click="handleMenuSetRecycle(row)"
          v-hasPermi="['customer:customerPool:setRecycle']"
          v-if="queryParams.isRecycle == false"
        />
        <context-menu-item
          label="恢复"
          @click="handleMenuRecyleRestore(row)"
          v-hasPermi="['customer:customerPool:recyleRestore']"
          v-if="queryParams.isRecycle == true"
        />
        <context-menu-item
          label="彻底删除"
          @click="handleMenuDeleted(row)"
          v-hasPermi="['customer:customerPool:deleted']"
          v-if="queryParams.isRecycle == true"
        />
        <context-menu-item
          label="领取"
          @click="handleMenuReceive(row)"
          v-hasPermi="['customer:customerPool:receive']"
        />
        <context-menu-item
          label="分配"
          @click="handleMenuAllocation(row)"
          v-hasPermi="['customer:customerPool:allocation']"
        />
        <context-menu-item
          label="发邮件"
          @click="handleMenuSendMail(row)"
          v-hasPermi="['customer:customerPool:sendMail']"
        />
        <context-menu-item
          label="一键营销"
          @click="handleMenuMarket(row)"
          v-hasPermi="['customer:customerPool:market']"
        />
      </template>
    </Table>
  </ContentWrap>

  <CustomerShow ref="showRef" />
  <CustomerPoolAllocation ref="poolAllactionRef" @success="getPage" />
  <MailMarketSelect ref="marketSelectRef" @success="getPage()" />
  <ErrorMessage ref="errorMessageRef" />
  <CustomerSendMailSelect ref="sendMailSelectRef" />
</template>
<script setup name="customerPool" lang="ts">
import CustomerPoolAllocation from './CustomerPoolAllocation.vue'
import ErrorMessage from '@/views/common/ErrorMeesage.vue'
import MailMarketSelect from '@/views/market/mailMarket/MailMarketSelect.vue'
import CustomerSendMailSelect from '@/views/customer/customer/CustomerSendMailSelect.vue'
import CustomerShow from '@/views/customer/customer/CustomerShow.vue'

import * as CustomerApi from '@/api/customer/customer'
import * as CustomerPoolApi from '@/api/customer/customerPool'
import * as DeptApi from '@/api/system/dept/dept'

import { SettingBusinessModuleEnum } from '@/utils/constants'
import { getKeyList } from '@pureadmin/utils'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { getBussinessModule } from '@/views/setting/businessField/BusinessFieldUtil'
const { wsCache } = useCache()

const recycleMessage = ref('回收站')
const { push } = useRouter() // 路由

const message = useMessage() // 消息弹窗
const showRef = ref()
const sendMailSelectRef = ref()
const marketSelectRef = ref()
const errorMessageRef = ref()
const poolAllactionRef = ref()
const tableRef = ref()

const queryFormRef = ref()
const queryParams = ref({
  customerNo: undefined,
  name: undefined,
  source: undefined,
  grade: undefined,
  stage: undefined,
  state: undefined,
  isRecycle: false,
  isFallPool: true
})
const queryData = ref()

let columns = ref<any[]>([
  {
    label: '客户编号',
    prop: 'customerNo',
    minWidth: '140'
  }
])

/** 初始化 */
onMounted(() => {
  dataInit()
  getPage()
})

const dataInit = async () => {
  columns.value = [
    {
      type: 'selection',
      alignWhole: 'center'
    },
    {
      label: '客户编号',
      prop: 'customerNo',
      minWidth: '140'
    },
    {
      label: '名称',
      prop: 'name'
    },
    {
      label: '公司主图片',
      prop: 'mainImageUrl',
      slot: 'mainImageUrl',
      minWidth: '140'
    },
    {
      label: '地址',
      prop: 'address'
    },

    {
      label: '所属人',
      prop: 'owner.nickname'
    },

    {
      label: '所属部门',
      prop: 'dept.name'
    },
    {
      label: '国家',
      prop: 'country.name'
    },
    {
      label: '上次跟进时间',
      prop: 'lastFollowTime'
    },
    {
      label: '上次发邮件时间',
      prop: 'lastSendMailTime'
    },
    {
      label: '调入公海时间',
      prop: 'fallPoolTime'
    },
    {
      label: '调入公海原因',
      prop: 'fallPoolReason'
    }
  ]
  // 加载业务字段
  const customerModuleField = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER)

  customerModuleField.immutableFields.forEach((item) => {
    columns.value.push({
      label: item.showName,
      prop: item.fieldName,
      formatter: (row) =>
        row[item.fieldName] == 0
          ? ''
          : item.options.find((obj) => obj.id === row[item.fieldName])?.name
    })
  })
  customerModuleField.customFields.forEach((item) => {
    columns.value.push({
      label: item.showName,
      prop: item.fieldName
    })
  })

  const contactModuleField = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER_CONTACT)
  contactModuleField.immutableFields.forEach((item) => {
    columns.value.push({
      label: '主联系人' + item.showName,
      prop: 'mainContact.' + item.fieldName,

      formatter: (row) =>
        row['mainContact'][item.fieldName] == 0
          ? ''
          : item.options.find((obj) => obj.id === row['mainContact'][item.fieldName])?.name
    })
  })

  contactModuleField.customFields.forEach((item) => {
    columns.value.push({
      label: '主联系人' + item.showName,
      prop: 'mainContact.' + item.fieldName
    })
  })

  columns.value = columns.value.concat([
    {
      label: '创建时间',
      prop: 'createTime'
    },
    {
      label: '上次修改时间',
      prop: 'updateTime'
    }
  ])

  recycleMessage.value = '回收站'
  queryParams.value = {
    customerNo: undefined,
    name: undefined,
    source: undefined,
    grade: undefined,
    stage: undefined,
    state: undefined,
    isRecycle: false,
    isFallPool: true
  }
}

/** 搜索按钮操作 */
const handleClickSearch = () => {
  getPage()
}

/** 重置按钮操作 */
const handleClickReset = () => {
  queryFormRef.value?.resetFields()
  handleClickSearch()
}

/** 处理响应事件  */
const getPage = async () => {
  queryData.value = await CustomerApi.pageQuery(queryParams.value)
}

const handleClickRecycle = () => {
  if (queryParams.value.isRecycle) {
    recycleMessage.value = '回收站'
    queryParams.value.isRecycle = false
  } else {
    recycleMessage.value = '返回列表'
    queryParams.value.isRecycle = true
  }
  getPage()
}

/** 处理右击事件 放入回收站 */
const handleMenuSetRecycle = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  await CustomerApi.setRecycle(rowIds)
  getPage()
}

/** 处理右击事件 回收站-恢复 */
const handleMenuRecyleRestore = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  await CustomerApi.restore(rowIds)
  getPage()
}

/** 处理右击事件 回收站-彻底删除 */
const handleMenuDeleted = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  await CustomerApi.deleted(rowIds)
  getPage()
}

const getMultipleSelect = (row) => {
  let selectRows = tableRef.value.getTableRef().getSelectionRows()
  if (row != null && !selectRows.includes(row)) selectRows.push(row)
  return selectRows
}

const handleClickReceive = () => {
  const selectRows = getMultipleSelect(null)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  handleReceive(rowIds)
}

const handleClickAllocation = () => {
  const selectRows = getMultipleSelect(null)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  handleAllocation(rowIds)
}

const handleMenuReceive = (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  handleReceive(rowIds)
}

const handleMenuAllocation = (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  handleAllocation(rowIds)
}

const handleAllocation = async (ids) => {
  if (ids.length == 0) {
    message.error('请选择客户')
    return
  }
  // 只有部门负责人可以分配
  let userInfo = wsCache.get(CACHE_KEY.USER)
  const isLeaderUser = await DeptApi.isLeaderUser(userInfo.user.id)
  if (!isLeaderUser) {
    message.error('只有部门负责人可以分配')
    return
  }

  poolAllactionRef.value.open(ids, userInfo.user.deptId)
}

const handleReceive = async (ids) => {
  if (ids.length == 0) {
    message.error('请选择客户')
    return
  }
  const errorInfo = await CustomerPoolApi.receive({ ids: ids })
  if (errorInfo != undefined && errorInfo.length > 0) {
    errorMessageRef.value.open({
      title: '领取错误列表',
      data: errorInfo,
      columns: [
        {
          label: '客户编号',
          prop: 'customerNo'
        },
        {
          label: '名称',
          prop: 'name'
        },
        {
          label: '错误原因',
          prop: 'message'
        }
      ]
    })
  } else {
    message.success('领取成功')
  }
  getPage()
}

const handleMenuSendMail = (row) => {
  sendMail(row)
}

const sendMail = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  if (rowIds.length == 0) {
    message.error('请选择客户')
    return
  }
  const mailInfos = await CustomerApi.getMailInfoByCustomerIds({ ids: [rowIds[0]] })
  if (mailInfos.length == 0) {
    await message.confirm('选择的客户没有邮件地址，确定要继续吗？')
    push({ name: 'MailEdit', state: { type: 'write' } })
  }
  if (mailInfos.length == 1) {
    push({
      name: 'MailEdit',
      state: {
        receivers: [{ name: mailInfos[0].contact.name, address: mailInfos[0].mailAddress }],
        type: 'customerSend'
      }
    })
  } else {
    sendMailSelectRef.value.open({
      customerName: selectRows[0]['name'],
      mailInfos: mailInfos
    })
  }
}

const handleMenuMarket = (row) => {
  customerMarket(row)
}

const customerMarket = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  if (rowIds.length == 0) {
    message.error('请选择客户')
    return
  }
  marketSelectRef.value.open(rowIds)
}

const handleTableClick = (row) => {
  showRef.value.open(row.id)
}
</script>
